package io.renren.common.utils;


import org.apache.commons.io.FilenameUtils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class FileUpload {
	
	//private static String URL="http://47.101.148.165:80/usr/local/xhyy/file/";
	private static String URL="/usr/fireExtinguishingSystem/filePath/";     //服务器地址

	//@Transactional(rollbackFor = Exception.class)
	public static R updateFile(MultipartFile[] file) {
			if (file == null) {
				R.error( "上传文件不能为空");
			}
			File targetFile = null;
			String url = "";//返回存储路径
			int code = 1;
			List imgList = new ArrayList();
			if (file != null && file.length > 0) {
				for (int i = 0; i < file.length; i++) {
					String fileName = file[i].getOriginalFilename();//获取文件名加后缀
					String caselsh = fileName.substring(0, fileName.lastIndexOf("."));
					if (fileName != null && fileName != "") {
						String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
						//String newFileName = numName + fileF;//新的文件名
						String newFileName = new Date().getTime() + "_" + new Random().nextInt(1000) + fileF;//新的文件名
						//获取后缀名
						/*String[] strArray = fileName.split("\\.");
						int suffixIndex = strArray.length -1;
						String fileType = strArray[suffixIndex];*/
						//动态生成文件
						Date date = new Date();
						String sdf = new SimpleDateFormat("yyyy-MM-dd").format(date);
						//String path = "D:"+File.separator+"home"+ File.separator + sdf;
						String path = URL+ File.separator + sdf;
						//如果文件夹不存在则创建
						File newFile = new File(path);
						if (!newFile.exists() && !newFile.isDirectory()) {
							newFile.mkdirs();
						}
						targetFile = new File(newFile, newFileName);
						try {
							//保存文件路径
							url=FilenameUtils.concat(path,newFileName);
							//获取输出流
							OutputStream os=new FileOutputStream(url);
							//获取输入流 CommonsMultipartFile 中可以直接得到文件的流
							InputStream is=file[i].getInputStream();
							int temp;
							//一个一个字节的读取并写入
							while((temp=is.read())!=(-1))
							{
								os.write(temp);
							}
							os.flush();
							os.close();
							is.close();
							String urlpath=url.replaceAll("\\\\","/");
							imgList.add(urlpath);
						/*	imgList.add(fileName);
							imgList.add(fileType);*/
							//   file[i].transferTo(targetFile);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}

			}
			System.out.println(imgList);

			return R.ok().put("data",imgList);
		}


}
